package com.jprocms.module.cms.config;

import com.jprocms.module.cms.inteceptor.FrontContextInterceptor;
import com.jprocms.module.cms.inteceptor.SiteContextInteceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static com.jprocms.module.cms.constant.InterceptorOrder.FRONT_INTERCEPTOR_ORDER;
import static com.jprocms.module.cms.constant.InterceptorOrder.SITE_INTERCEPTOR_ORDER;

/**
 * @author jprocms
 */
@Configuration(proxyBeanMethods = false)
public class PortalWebMvcConfig implements WebMvcConfigurer {
    private final SiteContextInteceptor siteContextInteceptor;
    private TplConfigProperties tplConfigProperties;

    private JproProperties jproProperties;

    public PortalWebMvcConfig(SiteContextInteceptor siteContextInteceptor, TplConfigProperties tplConfigProperties,JproProperties jproProperties) {
        this.siteContextInteceptor = siteContextInteceptor;
        this.tplConfigProperties = tplConfigProperties;
        this.jproProperties = jproProperties;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(siteContextInteceptor).addPathPatterns("/**")
                .excludePathPatterns("/doc.html", "/swagger-ui.html", "/v3/api-docs",
                        "/swagger-resources/**", "/webjars/**", "/u/**", "/res/**"
                        , "/rpc-api/**").order(SITE_INTERCEPTOR_ORDER);
        // 前台拦截器
        registry.addInterceptor(frontendInterceptor())
                .excludePathPatterns("/error/**", "/doc.html", "/swagger-ui.html", "/v3/api-docs",
                        "/swagger-resources/**", "/webjars/**", "/u/**", "/res/**").order(FRONT_INTERCEPTOR_ORDER);
    }

    /**
     * 前台拦截器
     */
    @Bean
    public FrontContextInterceptor frontendInterceptor() {
        return new FrontContextInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //本地上传资源映射  和文件配置的基础路径相同
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + jproProperties.getUploadPath()+"/upload");
        registry.addResourceHandler("/res/**")
                .addResourceLocations("file:" + tplConfigProperties.getTplLocalConfig().getResPath());
    }

}
